<?php

namespace app\uniapp\service;

use app\common\exception\MiException;
use app\common\service\CommonSiteConfigService;
use app\model\site\User;
use app\model\site\UserPointsLog;
use app\uniapp\service\traits\InstanceTrait;

class UserPointsLogService extends UniBaseService
{

    use InstanceTrait;

    function initialize()
    {
        $this->model = new UserPointsLog();
    }

    function formatData(array $data): array
    {
        return $data;
    }


    /**
     * 计算订单中的积分抵扣数据
     * @throws MiException
     */
    public function computeOrderPointsPrice(array $order): array
    {
        $pointsConfig = CommonSiteConfigService::instance()->getConfigValue($this->siteId, CommonSiteConfigService::POINTS);
        $user = User::find($this->userId);
        if (!$pointsConfig['is_on_dec']){ // 商城未开启积分抵扣
            return $order;
        }
        $pointsNum = $order['points_num'];
        if ($pointsNum == 0){   // 用户没有选择使用积分，直接返回订单信息
            return $order;
        }

        // 计算订单商品积分
        $maxPointsNum = 0;
        foreach ($order['items'] as &$v){
            // 抵扣积分数量向下取整，如果消耗的积分数量小于1不做抵扣，
            $v['maxPointsNum'] = floor($v['pay_price'] * $pointsConfig['money_rate']);
            $maxPointsNum += $v['maxPointsNum'];
        }
        // 实际可抵扣的积分数量
        $pointsNum = min($maxPointsNum, $user->points);
        // 计算实际积分数量和抵扣金额
        foreach ($order['items'] as &$v){
            $v['points_num'] = floor($v['maxPointsNum'] / $maxPointsNum* $pointsNum);
            // 取两位小数，后面的向下舍去
            $v['points_price'] = floor($v['points_num'] / $pointsConfig['money_rate']*100) / 100;
            $v['pay_price'] = $v['pay_price'] - $v['points_price'];
        }


        // 重新计算订单数据
        $totalPrice = 0;
        $payPrice = 0;
        $pointsPrice = 0;
        $pointsNum = 0;     //  订单中最终的积分数量
        foreach ($order['items'] as $item){
            $totalPrice += $item['total_price'];
            $payPrice += $item['pay_price'];
            $pointsPrice += $item['points_price'];
            $pointsNum += $item['points_num'];
        }
        $order['total_price'] = $totalPrice;
        $order['pay_price'] = $payPrice;
        $order['points_price'] = $pointsPrice;
        $order['points_num'] = $pointsNum;
        return $order;
    }

    public function createByOrder(){

    }
}
